<template>
  <div>
    <el-dialog v-model="dialogVisible" title="认证" width="30%" @close="closeDialog">
      <div>
        <!-- <div
          class="auth-box"
          v-for="(item, index) in typeList"
          :key="index"
          :class="{ 'auth-active': authorForm.type == item.value ,'auth-ban': item.value != userType && authentication == 2}"
          @click="changeType(item.value)"
        >
          {{ item.label }}
        </div> -->
        <div
          v-if="userType == 1"
          class="auth-box auth-active"         
          @click="changeType(1)"
        >
          个人证书
        </div>
        <div
          v-if="userType == 2"
          class="auth-box auth-active"                 
          @click="changeType(2)"
        >
          企业认证
        </div>
        <el-form
          v-show="userType == 1"
          :model="authorForm"
          ref="authorRef"
          :rules="authorRules"
          label-width="100px"
        >
          <el-form-item label="姓名" prop="realName">
            <el-input
              v-model="authorForm.realName"
              placeholder="请输入姓名"
              :maxlength="30"
            />
          </el-form-item>
          <el-form-item label="身份证号" prop="number">
            <el-input
              v-model="authorForm.number"
              placeholder="请输入身份证号"
              :maxlength="18"
            />
          </el-form-item>
          <el-form-item label="身份证照片" prop="certificatePath">
            <el-upload
              action=""
              :limit="1"
              v-model:file-list="idCard.cardFront"
              :show-file-list="false"
              :http-request="(file) => handleUpload(file, 'cardFront')"
            >
              <div v-if="idCard.cardFront.length == 0" class="upload-bg">
                <el-icon><Plus /></el-icon>
              </div>
              <div v-else>
                <el-image class="preImage" :src="idCard.cardFront[0].url" />
              </div>
            </el-upload>
            <el-upload
              action=""
              :limit="1"
              v-model:file-list="idCard.cardBack"
              :show-file-list="false"
              :http-request="(file) => handleUpload(file, 'cardBack')"
            >
              <div v-if="idCard.cardBack.length == 0" class="upload-bg">
                <el-icon><Plus /></el-icon>
              </div>
              <div v-else>
                <el-image class="preImage" :src="idCard.cardBack[0].url" />
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-form
          v-show="userType == 2"
          :model="authorForm"
          ref="businessRef"
          :rules="authorRules"
          label-width="120px"
        >
          <el-form-item label="统一信用代码" prop="number">
            <el-input
              v-model="authorForm.number"
              placeholder="请输入统一信用代码"
              :maxlength="50"
            />
          </el-form-item>
          <el-form-item label="单位名称" prop="realName">
            <el-input
              v-model="authorForm.realName"
              placeholder="请输入单位名称"
              :maxlength="30"
            />
          </el-form-item>
          <el-form-item label="通讯地址" prop="address">
            <el-input
              v-model="authorForm.address"
              placeholder="请输入通讯地址"
              :maxlength="30"
            />
          </el-form-item>
          <el-form-item label="营业执照" prop="certificatePath">
            <!-- <el-upload
              action=""
              :limit="1"
              v-model:file-list="certificatePath"
              :show-file-list="false"
              :http-request="(file) => handleUpload(file, 'certificatePath')"
            >
              <div v-if="certificatePath.length == 0" class="upload-bg">
                <el-icon><Plus /></el-icon>
              </div>
              <div v-else>
                <el-image class="preImage" :src="certificatePath[0].url" />
              </div>
            </el-upload> -->
            <el-upload
              v-model:file-list="fileList"
              action=""
              :limit="2"
              :class="{ hide: hideUploadBtn }"
              list-type="picture-card"
              accept=".jpg,.jpeg,.png"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="handleUploadByCertificatePath"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit(authorForm.type == 1 ? authorRef : businessRef)"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance , UploadUserFile} from 'element-plus'

import { postAuthen } from "@/api/loginApi";
import { upload } from "@/api/cloud/index";

const props = defineProps({
  // 是否显示
  show: {
    type: Boolean,
    default: false,
  },
  //用户类型
  userType:{
    type: Number,
    default:''
  },
  //重新认证
  authentication: {
    type: Number,
    default: 0
  }
});

const emits = defineEmits(["update:show", "change"]);
const dialogVisible = computed(() => props.show); // 控制弹窗显示
const userType = computed(() => props.userType); // 控制弹窗显示
const fileList = ref<UploadUserFile[]>([]); //上传营业执照
const hideUploadBtn = ref(false); //隐藏上传按钮开关
const fileNameList = ref<any>([]); //营业执照fileName数组
const imgUrl = ref("");
const imgShow = ref(false);

const baseURL = import.meta.env.VITE_BASE_URL;
const authorForm = ref<any>({
  type: 1,
  realName: "", // 真实姓名 / 企业名称
  number: "", // 身份证号 / 统一信用代码
  certificatePath: "", // 身份证照片 / 营业执照
  address: "",
});
const idCard = ref({
  cardFront: <any>"", // 身份证正面
  cardBack: <any>"", // 身份证反面
});
const certificatePath = ref<any>([]); // 营业执照
// const typeList = ref([
//   { label: "个人证书", value: 1 },
//   { label: "企业证书", value: 2 },
// ]);
const authorRef = ref<FormInstance>();
const businessRef = ref<FormInstance>();
const authorRules = ref<any>({
  realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  number: <any>[],
  certificatePath: <any>[],
});

watch(dialogVisible, (val) => {
  if (val) {
    changeType(userType.value);
  }
});

// 移除营业执照
const handleRemove = (file: any) => {
  fileList.value = fileList.value.filter((item) => item != file.name);
  fileNameList.value = fileNameList.value.filter((item) => item != file.name);
  authorForm.value.certificatePath = fileNameList.value.join(",");
  if (fileList.value.length < 2) {
    hideUploadBtn.value = false;
  } else {
    hideUploadBtn.value = true;
  }
};

// 预览营业执照
const handlePreview = (file: any) => {
  imgUrl.value = file.url;
  imgShow.value = true;
};

// 可以获取图片参数
const handleUploadByCertificatePath = (file: any) => {
  const formData = new FormData();
  formData.append("file", file);
  upload(formData).then((res: any) => {
    fileNameList.value.push(res.fileName);
    authorForm.value.certificatePath = fileNameList.value.join(",");
    fileList.value.push({ name: res.fileName, url: baseURL + res.fileName });
    if (fileList.value.length < 2) {
      hideUploadBtn.value = false;
    } else {
      hideUploadBtn.value = true;
    }
  });
};

// 关闭弹窗
const closeDialog = () => {
  emits("update:show", false);
  authorForm.value = <any>{
    type: 1,
    realName: "",
    number: "",
    certificatePath: "", // 身份证照片
    address: "",
  };
  idCard.value = <any>{
    cardFront: [], // 身份证正面
    cardBack: [], // 身份证反面
  };
  certificatePath.value = []; // 营业执照
};

// 切换认证类型
const changeType = (val) => {
  authorForm.value.type = val;
  authorForm.value = {
    type: val,
    realName: "",
    number: "",
    certificatePath: "",
    address: "",
  };
  if (val == 2) {
    authorRules.value.number = [
      { required: true, message: "请输入统一信用代码", trigger: "blur" },
    ];
    authorRules.value.certificatePath = <any>[
      { required: true, message: "请上传营业执照", trigger: "blur" },
    ];
  } else {
    authorRules.value.number = [
      { required: true, message: "请输入身份证号码", trigger: "blur" },
      {
        pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        message: "请输入正确的身份证号码",
        trigger: "blur",
      },
    ];
    authorRules.value.certificatePath = <any>[
      { required: true, message: "请上传身份证照片", trigger: "blur" },
    ];
  }
  setTimeout(() => {
    resetForm(val == 1 ? authorRef.value : businessRef.value)
  }, 0);
};

// 可以获取图片参数
const handleUpload = (file: any, field: any) => {
  const formData = new FormData();
  formData.append("file", file.file);
  upload(formData).then((res: any) => {
    if (field == "business") {
      certificatePath.value = <any>[{ url: baseURL + res.fileName }];
      authorForm.value.certificatePath = res.fileName;
    } else {
      idCard.value[field] = [{ url: baseURL + res.fileName }];
      const { cardFront, cardBack } = idCard.value;
      if (cardFront.length && cardBack.length) {
        authorForm.value.certificatePath = cardFront[0].url + "," + cardBack[0].url;
      }
    }
  });
};

// 提交认证
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      postAuthen(authorForm.value).then((res) => {
        ElMessage.success("认证已提交");
        closeDialog();
        emits("change");
      });
    }
  });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
<style lang="less" scoped>
.hide {
  /deep/.el-upload--picture-card {
    display: none !important;
  }
}
//去掉过渡动画，不然删除操作的时候，布局会闪一下。
/deep/ .el-upload-list__item {
  transition: none !important;
}
.upload-bg {
  width: 148px;
  height: 148px;
  border-radius: 8px;
  background-color: #fafafa;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d5d8dd;
  margin-bottom: 10px;
  margin-right: 10px;
}
.preImage {
  width: 148px;
  height: 148px;
  border-radius: 8px;
  margin-right: 10px;
}
.auth-box {
  display: inline-block;
  border: 1px solid #e4e4e4;
  width: 120px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 20px;
  margin-right: 10px;
  margin-bottom: 20px;
  &:hover {
    cursor: pointer;
  }
}
.auth-active {
  background-color: #f0f7ff;
  color: #409eff;
  border: 1px solid #409eff;
}
</style>
